package com.lkwlw.tplms.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import com.lkwlw.tplms.mapper.CustomerinfoMapper;
import com.lkwlw.tplms.model.Customerinfo;
import com.lkwlw.tplms.model.CustomerinfoExample;
import com.lkwlw.tplms.model.CustomerinfoExample.Criteria;
import com.lkwlw.tplms.model.Pager;
import com.lkwlw.tplms.system.dao.model.Admininfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {
	
	private static final long serialVersionUID = -4541502010102975296L;
	private Customerinfo customer;
	private CustomerinfoMapper customerDAO;
	private List<Customerinfo> customerList;
	private String selectIds;
	private String areaLabels;
	private String areaValues;
	private Pager pager;
	private int page;
	//private final Logger log = Logger.getLogger(CustomerAction.class);
	
	
	
	public String execute()throws Exception{
		clearCustomer();
		selectIds = null;
		areaLabels = "";
		areaValues = "||"; // 页面省市区组件初始值为空时，组件的默认值
		return SUCCESS;
	}
	public String edit() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("editCustomerId");
		System.out.println(id);
		clearCustomer();
		customer = customerDAO.selectByPrimaryKey(Integer.parseInt(id));
		selectIds = String.valueOf(customer.getSex());
		areaValues = customer.getProvincecode() + "|";
		String cityCode = (customer.getCity() == null && "".equals(customer.getCity()))? "" : customer.getCitycode();
		areaValues += cityCode + "|";
		
		areaValues += customer.getDistrictcode();
		return SUCCESS;
	}
	public String save()throws Exception{
		ActionContext context = ActionContext.getContext();
		Map session = context.getSession();
		Admininfo admin = (Admininfo) session.get("admin");
		String[] labels = areaLabels.split(",");
		String[] values = areaValues.split(",");
		customer.setProvince(labels[0]);
		customer.setProvincecode(values[0]);
		if(values[1].equals("")){
			customer.setCity(null);
			customer.setCitycode(null);
		}else{
			customer.setCity(labels[1]);
			customer.setCitycode(values[1]);
		}
		customer.setDistrict(labels[2]);
		customer.setDistrictcode(values[2]);
		if (admin != null) {
			customer.setRegistrant(admin.getFullName());
			if(customer.getId() == 0){
				customerDAO.insert(customer);
			}else{
				customerDAO.updateByPrimaryKey(customer);
			}			
			clearActionParam();
			list();
			return SUCCESS;
		}		
		return ERROR;
	}
	public String query() throws Exception{
		CustomerinfoExample example = new CustomerinfoExample();
		Criteria criteria = example.createCriteria();
		if (null != areaValues && !"".equals(areaValues)) {
			String[] values = areaValues.split(",");
//			System.out.println(values.length);
//			customer.setProvincecode(values[0].equals("-") ? "" : values[0]);
//			customer.setCitycode(values[1].equals("-") ? "" : values[1]);
//			customer.setDistrictcode(values[2].equals("-") ? "" : values[2]);
			if(!values[0].equals("-")) {
				criteria.andProvincecodeEqualTo(values[0]);
			}
			if (!values[1].equals("-")) {
				criteria.andCitycodeEqualTo(values[1]);
			}
			if (!values[2].equals("-")) {
				criteria.andDistrictcodeEqualTo(values[2]);
			}
		}
		if (customer != null) {
			if(null != customer.getName() && !"".equals(customer.getName())){
				criteria.andNameLike("%"+customer.getName()+"%");
			}
			if (null != customer.getCompany() && !"".equals(customer.getCompany())) {
				criteria.andCompanyLike("%"+customer.getCompany()+"%");
			}			
		}	
		example.setOrderByClause("name");
		getPagination(example);
		clearActionParam();
		return SUCCESS;
	}
	private void clearActionParam(){
		areaLabels = "";
		areaValues = "";
		selectIds = "";
		clearCustomer();
	}
	private void getPagination(CustomerinfoExample example){
		int pageSize=10;
		pager.setCurrentPage(page);
		pager.setPageSize(pageSize);
		
		// 获得总记录数
		int totalSize = customerDAO.countByExample(example);
		pager.setTotalCount(totalSize);
		Map<String, Integer> limitParam = new HashMap<String, Integer>();
		limitParam.put("offset", pager.getStart());
		limitParam.put("rows", pager.getPageSize());
		
		customerList = null;		
		customerList = customerDAO.selectByExample(limitParam,example);
		pager.setItems(customerList);
		pager.setPaginationModel(getPagerStr(totalSize));		
	}
	
	public String delete() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String ids = request.getParameter("deleteCustomerIds");
		String[] deleteIds = ids.split(",");
		for (int i = 0; i < deleteIds.length; i++) {
			customerDAO.deleteByPrimaryKey(Integer.valueOf(deleteIds[i]));
		}
		list();
		return SUCCESS;
	}
	
	// 列出所有信息
	public String list()throws Exception{
		page = 1;
		CustomerinfoExample example = new CustomerinfoExample();
		example.setOrderByClause("name");
		getPagination(example);
		return SUCCESS;
	}
	
	/**
	 * 组织分页导航栏
	 * @return
	 */
	public String  getPagerStr(int totalSize) {
		
		StringBuilder sb=new StringBuilder();
		
		int pageCount=pager.getTotalPage();//总页数
		int a_total=10;      //分页条中有多少个超链接
		
		sb.append("<table><tr><td align='center'class='wordblue'>共" + pager.getTotalCount()+"条数据&nbsp;&nbsp;页次");
		sb.append(pager.getCurrentPage()+"/" + (totalSize == 0 ? 1 : pageCount) + "页&nbsp;&nbsp;</td>");
		//实际应用中修改上面第三个参数即可
		double total = a_total/2;
		int a_padding=(int)Math.ceil(total);  //中间的那个超链接距离边缘链接的间隔a的个数 例如：共11个分页 那么这个就是5

		if(pageCount - pager.getCurrentPage() <= a_padding && pager.getCurrentPage() > a_padding + 1) {
			a_padding=a_total-(pageCount-pager.getCurrentPage());
		}

		int start=pager.getCurrentPage()-a_padding,
		end=start+a_total;
		

		if(pager.getCurrentPage() > 1){
			sb.append("<td class='wordblue'><a href=queryCustomer?page=1>首页</a>&nbsp;&nbsp;</td>");
			sb.append("<td ><div class='prepage wordblue'><a href=queryCustomer?page="+(pager.getCurrentPage()-1)+">上一页</a></div></td>");
		}
		sb.append("<td ><div class='pagelist'>");
		if (totalSize > 0) {
			for (int i = start; i <=end; i++) {
				if(i<=0){
					end+=Math.abs(i);
					i=1;	
				}
				sb.append(" <a href=queryCustomer?page=" + i + " " + ( i == pager.getCurrentPage() ? "style=\"color:red;\"":"") + "> " + i + " </a>");	
				if(i==pageCount){
					break;
				}
			}
		}		
		sb.append("</div></td>");
		if(pager.getCurrentPage()-pageCount<0){
			sb.append("<td><div class='nextpage wordblue'>");
			sb.append("<a href=queryCustomer?page=" + ( pager.getCurrentPage() + 1 ) + ">下一页</a></div></td>");
			sb.append("<td><div class='wordblue'><a href=queryCustomer?page=" + pageCount + ">尾页</a></div></td>");
			}
		sb.append("</tr></table>");
		return sb.toString();
	}
	
	public void clearCustomer(){
		customer.setId(0);
		customer.setSex(0);
		customer.setName(null);
		customer.setCompany(null);
		customer.setTelephone(null);
		customer.setProvince("");
		customer.setProvincecode("");
		customer.setCity("");
		customer.setCitycode("");
		customer.setDistrict("");
		customer.setDistrictcode("");
		customer.setAddress(null);
		customer.setRegistrant(null);
		customer.setRegisterdate(null);
	}
	
	public Customerinfo getCustomer() {
		return customer;
	}
	public void setCustomer(Customerinfo customer) {
		this.customer = customer;
	}
	public CustomerinfoMapper getCustomerDAO() {
		return customerDAO;
	}
	public void setCustomerDAO(CustomerinfoMapper customerDAO) {
		this.customerDAO = customerDAO;
	}
	public List<Customerinfo> getCustomerList() {
		return customerList;
	}
	public void setCustomerList(List<Customerinfo> customerList) {
		this.customerList = customerList;
	}
	public String getSelectIds() {
		return selectIds;
	}
	public void setSelectIds(String selectIds) {
		this.selectIds = selectIds;
	}
	public String getAreaLabels() {
		return areaLabels;
	}
	public void setAreaLabels(String areaLabels) {
		this.areaLabels = areaLabels;
	}
	public String getAreaValues() {
		return areaValues;
	}
	public void setAreaValues(String areaValues) {
		this.areaValues = areaValues;
	}
	public Pager getPager() {
		return pager;
	}
	public void setPager(Pager pager) {
		this.pager = pager;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	
	public static void main(String[] args) {
		String test1 = "-,,-";
		String[] test2 = test1.split(",");
		System.out.println(test2.length);
	}
}
